// pages/pay/pay.js
import request from '../../utils/request'
import {
  setToken,
  getToken
} from '../../utils/auth'
Component({
  /**
   * 组件的初始数据
   */
  data: {
    show: false,
    productList: [],
    totalPrice: 0
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onLoad(options) {
      const productList = JSON.parse(decodeURIComponent(options.detail))
      this.setData({
        totalPrice: productList.reduce((pre, next) => {
          return pre + next.goods_price * next.num
        }, 0),
        productList
      })
    },
    onClose() {
      this.setData({
        show: false
      });
    },
    async createOrder(token) {

      try {
        const address = wx.getStorageSync('address');
        const {
          order_number
        } = await request({
          url: '/my/orders/create',
          method: 'post',
          data: {
            order_price: this.data.totalPrice,
            consignee_addr: address,
            goods: this.data.productList.map(item => ({
              goods_id: item.goods_id,
              goods_number: item.num,
              goods_price: item.goods_price
            }))
          }
        })
        const {
          pay
        } = await request({
          url: '/my/orders/req_unifiedorder',
          method: "post",
          data: {
            order_number
          }
        })
        wx.requestPayment({
          ...pay,
          success: async () => {
            await request({
              url: "/my/ordes/chkOrder",
              method: 'post',
              data: {
                order_number
              }
            })
            wx.showToast({
              title: '支付成功',
              icon: 'success'
            })
            const shopcart = wx.getStorageSync('shopcart')
            const productList = shopcart.filter(item => !this.data.productList.find(productItem => productItem.goods_id === item.goods_id))
            wx.setStorageSync('shopcart', productList)
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 1000)
          }
        })

      } catch (error) {
        // 模拟跳转
        const shopcart = wx.getStorageSync('shopcart')
        const productList = shopcart.filter(item => !this.data.productList.find(productItem => productItem.goods_id === item.goods_id))
        wx.setStorageSync('shopcart', productList)
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
          })
        }, 1000)
        wx.showToast({
          title: '支付失败',
          icon: 'none'
        })
      }

    },
    getToken(e) {
      wx.login({
        timeout: 10000,
        success: async (result) => {
          let {
            encryptedData,
            rawData,
            iv,
            signature
          } = e;
          const {
            code
          } = result
          try {
            const res = await request({
              url: '/users/wxlogin',
              method: 'post',
              data: {
                encryptedData,
                rawData,
                iv,
                signature,
                code
              }
            })
            if (res) {
              setToken(res.token)
              this.createOrder(res.token)
            }


          } catch (error) {
            // 模拟跳转
            const shopcart = wx.getStorageSync('shopcart')
            const productList = shopcart.filter(item => !this.data.productList.find(productItem => productItem.goods_id === item.goods_id))
            wx.setStorageSync('shopcart', productList)
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 1000)
          }
        }
      })
    },
    //点击支付按钮
    handleOrderPay() {
      // 获取用户的 token
      let token = getToken()
      //如果用户 token 不存在的情况下
      if (!token) {
        wx.getUserInfo({
          success: async (e) => {
            this.getToken(e)
          },
          fail: () => {
            this.setData({
              show: true
            })
          }
        })
      } else {
        this.createOrder(token)
      }
    },
    async handleGetUserInfo(e) {
      this.getToken(e)
    }
  }
})